<template>
    <el-card>
        <div class="title">
            <h4>部门管理</h4>
            <el-button @click="addDialogVisible = true">新增部门</el-button>
        </div>

        <el-table :data="state.deptList" height="350" style="width: 100%">
            <el-table-column type="index" label="序号" width="180" />
            <el-table-column prop="name" label="部门名称" width="180" />
            <el-table-column prop="tel" label="部门电话" width="180" />
            <el-table-column prop="principal" label="负责人" width="180" />
            <el-table-column prop="principal_tel" label="负责人电话" width="180" />
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button type='warning' size="small" icon="Edit" @click="getDeptInfo(scope.row.id)">编辑</el-button>
                    <el-button type='danger' size="small" icon="Delete" @click="delDept(scope.row.id)">删除</el-button>
                </template>

            </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="pageParam.pageNum" v-model:page-size="pageParam.pageSize"
            :page-sizes="[5, 10, 15, 20]" :small="small" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handlepageSizeChange"
            @current-change="handlepageNumChange" />

    </el-card>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="部门新增" width="500">


        <el-form ref="ruleFormRef" style="max-width: 600px" :model="addForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>

            <el-form-item label="部门名称" prop="name">
                <el-input v-model="addForm.name" />
            </el-form-item>

            <el-form-item label="负责人姓名" prop="principal">
                <el-input v-model="addForm.principal" />
            </el-form-item>

            <el-form-item label="负责人电话" prop="principal_tel">
                <el-input v-model="addForm.principal_tel" />
            </el-form-item>

            <el-form-item label="部门电话" prop="tel">
                <el-input v-model="addForm.tel" />
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelForm(ruleFormRef)">Cancel</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="部门编辑" width="500">


        <el-form ref="ruleFormRef" style="max-width: 600px" :model="editForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>

            <el-form-item label="部门名称" prop="name">
                <el-input v-model="editForm.name" />
            </el-form-item>

            <el-form-item label="负责人姓名" prop="principal">
                <el-input v-model="editForm.principal" />
            </el-form-item>

            <el-form-item label="负责人电话" prop="principal_tel">
                <el-input v-model="editForm.principal_tel" />
            </el-form-item>

            <el-form-item label="部门电话" prop="tel">
                <el-input v-model="editForm.tel" />
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editDialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="submiteditForm(ruleFormRef)">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { inject, onMounted, ref, reactive } from "vue";
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { getDeptListInfo, addDept, deleteDept, getDeptInfoById, editDeptById } from '../../api/dept/dept.ts'
const $http: any = inject("$http")

//部门数据
const state = reactive({
    deptList: [],
    total: 0
})

//获取部门数据
const getDeptList = async () => {
    // const { data } = await $http.get(`/deps?pageNum=${pageParam.pageNum}&pageSize=${pageParam.pageSize}`)
    const { data } = await getDeptListInfo(pageParam)
    state.deptList = data.data.rows;
    state.total = data.data.total
    // ElNotification({
    //     title: 'Success',
    //     message: '部门获取成功',
    //     type: 'success',
    //     duration: 500,
    //     position: 'top-right',
    //     offset: 100
    // })
}

onMounted(() => {
    getDeptList()
})

//分页参数
const pageParam = reactive({
    //当前是第几页 pageNum
    pageNum: 1,
    //每页显示多少条
    pageSize: 5
})
const small = ref(false)
const background = ref(true)
const handlepageNumChange = (val: number) => {
    console.log(`当前的page: ${val}`)
    pageParam.pageNum = val
    getDeptList()
}
const handlepageSizeChange = (val: number) => {
    console.log(`每页的条数: ${val} `)
    pageParam.pageSize = val
    getDeptList()
}


// 部门新增对话框
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 定义部门数据接口
interface RuleForm {
    name: string,
    principal: string,
    principal_tel: string,
    tel: string,
}
// 定义部门表单数据对象
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const addForm = reactive<RuleForm>({
    name: '',
    principal: "",
    principal_tel: "",
    tel: ""
})

const editForm = reactive<RuleForm>({
    name: '',
    principal: "",
    principal_tel: "",
    tel: ""
})

// 定义校验规则,同样是响应式。
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入部门名称', trigger: 'blur' },
        { min: 3, max: 6, message: '部门名称的长度在3到6之间', trigger: 'blur' },
    ],
    principal: [
        { required: true, message: '请输入负责人姓名', trigger: 'blur' },
        { min: 2, max: 5, message: '负责人姓名的长度在2到5之间', trigger: 'blur' },
    ],
    principal_tel: [
        { required: true, message: '请输入负责人电话', trigger: 'blur' },
        { min: 8, max: 11, message: '负责人电话的长度在8到11之间', trigger: 'blur' },
    ],
    tel: [
        { required: true, message: '请输入部门电话', trigger: 'blur' },
        { min: 8, max: 11, message: '部门电话的长度在8到11之间', trigger: 'blur' },
    ]
})

// 确定添加功能
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        //校验通过则执行的逻辑
        if (valid) {
            // const { data } = await $http.post("/dep", addForm)
            const { data } = await addDept(addForm);
            if (data.code === 200) {
                addDialogVisible.value = false
                ElMessage({
                    showClose: true,
                    message: '添加部门成功',
                    type: 'success',
                    duration: 1000,
                })
                resetForm(formEl)
                getDeptList()
            }
            // 不通过执行的逻辑
        } else {
            ElMessage({
                showClose: true,
                message: '请认真校验参数信息',
                type: 'error',
                duration: 1000,
            })
        }
    })
}
// 取消添加功能
const cancelForm = async (formEl: FormInstance | undefined) => {
    addDialogVisible.value = false

    resetForm(formEl)
}
// 表单重置功能
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


// 部门删除功能
function delDept(id: string) {
    ElMessageBox.confirm(
        '真的删除吗？',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            // const { data } = await $http.delete(`/dep/${id}`)
            const { data } = await deleteDept(id)
            if (data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }
            getDeptList()

        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '删除取消',
            })
        })
}

const currentEditId = ref("")

//编辑功能
const getDeptInfo = async (id: string) => {
    editDialogVisible.value = true
    currentEditId.value = id;
    //根据ID获取部门信息
    // const { data } = await $http.get(`/dep/${id}`)
    const { data } = await getDeptInfoById(id);
    editForm.name = data.data.name;
    editForm.principal = data.data.principal;
    editForm.principal_tel = data.data.principal_tel;
    editForm.tel = data.data.tel;
}

// 确定编辑修改功能
const submiteditForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        //校验通过则执行的逻辑
        if (valid) {
            // const { data } = await $http.put(`/dep/${currentEditId.value}`, editForm)
            const { data } = await editDeptById(currentEditId.value,editForm)
            if (data.code === 200) {
                editDialogVisible.value = false
                ElMessage({
                    showClose: true,
                    message: '修改部门信息成功',
                    type: 'success',
                    duration: 1000,
                })
                getDeptList()
            }
            // 不通过执行的逻辑
        } else {
            ElMessage({
                showClose: true,
                message: '请认真校验参数信息',
                type: 'error',
                duration: 1000,
            })
        }
    })
}
</script>

<style scoped lang="less">
.title {
    display: flex;
    height: 40px;
    border-bottom: 1px dashed #ddd;
    justify-content: space-between
}

.el-card {
    padding: 10px;
}

.el-pagination {
    margin-top: 25px;
}
</style>